<template>
  <div ref="boxRef" class="chart-box trend-box">
    <div class="chart-header">
      <div class="title-wrapper">
        <h3>
          <span class="title-icon">|</span>
          <span>{{ currentTitle }}</span>
          <svg class="dropdown-icon" viewBox="0 0 1024 1024" width="12" height="12" @click.stop="toggleDropdown">
            <path
              d="M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3 0.1-12.7-6.4-12.7z"
              fill="#8492a6"
            />
          </svg>
        </h3>
        <!-- 下拉菜单 -->
        <div v-if="showDropdown" class="dropdown-menu" @click.stop>
          <div 
            v-for="item in trendTypes" 
            :key="item.key"
            class="dropdown-item"
            :class="{ active: currentType === item.key }"
            @click="switchTrendType(item.key)"
          >
            {{ item.text }}
          </div>
        </div>
      </div>
      <button class="fullscreen-btn" @click="toggleFullscreen">⛶</button>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch, computed } from 'vue';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';
import { subscribeToChart } from '@/services/dataHub';

const props = defineProps<{ isDarkTheme: boolean }>();

const chartRef = ref<HTMLElement | null>(null);
const boxRef = ref<HTMLElement | null>(null);
const currentType = ref('map'); // 当前趋势类型：map, seller, commodity
const showDropdown = ref(false);
let chart: echarts.ECharts | null = null;
let resizeHandler: (() => void) | null = null;
let fullscreenTimer: number | null = null;

// 颜色常量 - 顺序:绿、蓝、青、红、橙
const LINE_COLORS = ['rgba(11,168,44)', 'rgba(44,110,255)', 'rgba(22,242,217)', 'rgba(254,33,30)', 'rgba(250,105,0)'];
const AREA_COLORS = ['rgba(11,168,44,0.4)', 'rgba(44,110,255,0.4)', 'rgba(22,242,217,0.4)', 'rgba(254,33,30,0.4)', 'rgba(250,105,0,0.4)'];
const AREA_COLORS_BOTTOM = ['rgba(11,168,44,0.02)', 'rgba(44,110,255,0.02)', 'rgba(22,242,217,0.02)', 'rgba(254,33,30,0.02)', 'rgba(250,105,0,0.02)'];

// 保留接口原有数据
let originalData: any = null;
let rawTrendData: any = null;

const deepClone = <T,>(value: T): T => JSON.parse(JSON.stringify(value));

// 趋势类型列表
const trendTypes = computed(() => {
  if (!originalData?.type) {
    return [
      { key: 'map', text: '地区销量趋势' },
      { key: 'seller', text: '商家销量趋势' },
      { key: 'commodity', text: '商品销量趋势' }
    ];
  }
  return originalData.type;
});

// 当前标题
const currentTitle = computed(() => {
  const type = trendTypes.value.find((t: any) => t.key === currentType.value);
  return type?.text || '地区销量趋势';
});

const disposeChart = () => {
  if (chart && !chart.isDisposed()) {
    chart.dispose();
  }
  chart = null;
};

const applyCategoryToTrend = () => {
  if (!rawTrendData) return;
  const cloned = deepClone(rawTrendData);
  originalData = cloned;
  updateChartOption();
};

let unsubscribe: (() => void) | null = null;

// 请求接口（改用 WebSocket）
function setupTrendDataSubscription() {
  unsubscribe = subscribeToChart('trend', (data: any) => {
    // 只在数据内容变化时重置 currentType
    const oldKeys = rawTrendData ? Object.keys(rawTrendData) : [];
    rawTrendData = data;
    const newKeys = rawTrendData ? Object.keys(rawTrendData) : [];
    if (oldKeys.length !== newKeys.length) {
      currentType.value = 'map'; // 或默认类型
    }
    applyCategoryToTrend();
  });
}

// 切换趋势类型
function switchTrendType(type: string) {
  currentType.value = type;
  showDropdown.value = false;
  updateChartOption();
}

// 更新图表配置
function updateChartOption() {
  if (!chart || !originalData) return;

  const typeData = originalData[currentType.value];
  const commonData = originalData.common;

  // 构建series数据
  const series = typeData.data.map((item: any, index: number) => {
    const colorIdx = index < LINE_COLORS.length ? index : LINE_COLORS.length - 1;
    return {
      name: item.name,
      type: 'line',
      smooth: true,
      showSymbol: false,
      stack: 'Total', // 堆叠显示
      data: item.data.map((val: string) => parseFloat(val)),
      lineStyle: { color: LINE_COLORS[colorIdx], width: 2.5 },
      areaStyle: {
        opacity: 0.8,
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: AREA_COLORS[colorIdx] },
            { offset: 1, color: AREA_COLORS_BOTTOM[colorIdx] },
          ],
        } as any
      },
      emphasis: {
        focus: 'series'
      },
      symbol: 'none',
      z: index + 1,
    };
  });

  // 计算堆叠后的最大值
  const monthCount = commonData.month.length;
  let maxStackValue = 0;
  
  for (let i = 0; i < monthCount; i++) {
    let stackSum = 0;
    for (const item of typeData.data) {
      stackSum += parseFloat(item.data[i]);
    }
    maxStackValue = Math.max(maxStackValue, stackSum);
  }

  // Y轴最大值为最高点加50
  const yAxisMax = Math.ceil(maxStackValue + 50);
  // 计算合适的间隔(大约分成5-6段)
  const yAxisInterval = Math.ceil(yAxisMax / 5);

  const tooltipFormatter = (rawParams: any) => {
    const params = Array.isArray(rawParams) ? rawParams : [rawParams];
    if (!params.length) return '';
    const axisValue = params[0].axisValue;
    const lines = params
      .map((item: any) => {
        const value = Number.isFinite(item.data) ? item.data : '-';
        return `<div style="display:flex;align-items:center;gap:8px;">` +
          `<span style="width:12px;height:12px;border-radius:6px;background:${item.color};display:inline-block;"></span>` +
          `<span style="flex:1;">${item.seriesName}</span>` +
          `<span style="font-weight:600;">${value}</span>` +
        `</div>`;
      })
      .join('');
    return `<div style="min-width:180px;">` +
      `<div style="font-weight:600;margin-bottom:6px;">${axisValue}</div>` +
      `${lines}` +
    `</div>`;
  };

  const option: EChartsOption = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: 'rgba(0, 150, 255, 0.85)',
          padding: [4, 6],
          borderRadius: 4,
          fontSize: 11,
        },
      },
      backgroundColor: 'rgba(15, 28, 45, 0.92)',
      borderColor: 'rgba(0, 150, 255, 0.35)',
      borderWidth: 1,
      textStyle: { color: '#f0f6ff', fontSize: 12 },
      extraCssText: 'box-shadow:0 6px 16px rgba(0,0,0,0.35);border-radius:10px;padding:12px 14px;',
  formatter: tooltipFormatter as any,
    },
    legend: {
      data: typeData.data.map((item: any, index: number) => {
        const colorIdx = index < LINE_COLORS.length ? index : LINE_COLORS.length - 1;
        return {
          name: item.name,
          itemStyle: {
            color: LINE_COLORS[colorIdx]
          }
        };
      }),
      textStyle: { color: props.isDarkTheme ? '#b0c4de' : '#333', fontSize: 12 },
      top: 5,
      itemWidth: 12,
      itemHeight: 12,
      icon: 'circle',
    },
    grid: { top: '8%', left: '3%', right: '3%', bottom: '8%', containLabel: true },
    xAxis: {
      type: 'category',
      data: commonData.month,
      axisLine: { lineStyle: { color: props.isDarkTheme ? '#2f4554' : '#ddd' } },
      axisLabel: { color: props.isDarkTheme ? '#8492a6' : '#666', fontSize: 11 },
      splitArea: { show: false },
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: yAxisMax,
      interval: yAxisInterval,
      axisLine: { show: false },
      axisLabel: { color: props.isDarkTheme ? '#8492a6' : '#666', fontSize: 11 },
      splitLine: { lineStyle: { color: props.isDarkTheme ? '#233a4d' : '#f0f0f0', type: 'dashed' } },
      splitArea: { show: false },
    },
    series: series,
  };

  chart.setOption(option);
}

// 切换下拉菜单
function toggleDropdown() {
  showDropdown.value = !showDropdown.value;
}

const initChart = () => {
  if (!chartRef.value) return;

  disposeChart();
  chart = echarts.init(chartRef.value);

  // 如果已有数据则更新
  if (originalData) {
    updateChartOption();
  }

  if (!resizeHandler) {
    resizeHandler = () => {
      chart?.resize();
    };
    window.addEventListener('resize', resizeHandler);
  }
};

const toggleFullscreen = () => {
  const box = boxRef.value;
  if (!box) return;
  const button = box.querySelector('.fullscreen-btn') as HTMLButtonElement | null;

  if (!box.classList.contains('fullscreen')) {
    box.classList.add('fullscreen');
    if (button) button.textContent = '✕';
    fullscreenTimer = window.setTimeout(() => {
      chart?.resize();
    }, 300);
    window.addEventListener('keydown', escListener);
  } else {
    box.classList.remove('fullscreen');
    if (button) button.textContent = '⛶';
    fullscreenTimer = window.setTimeout(() => {
      chart?.resize();
    }, 300);
    window.removeEventListener('keydown', escListener);
  }
};

function escListener(e: KeyboardEvent) {
  if (e.key === 'Escape') {
    const box = boxRef.value;
    if (box && box.classList.contains('fullscreen')) {
      toggleFullscreen();
    }
  }
}

watch(
  () => props.isDarkTheme,
  () => {
    initChart();
  }
);

// Watch for dark theme changes - need to reinit chart
watch(() => props.isDarkTheme, () => {
  initChart();
});

// Watch for trend type changes - only update option
watch(currentType, () => {
  if (originalData) {
    updateChartOption();
  }
});

onMounted(() => {
  setupTrendDataSubscription();
  initChart();
  
  // 点击外部关闭下拉菜单
  document.addEventListener('click', (e: MouseEvent) => {
    const target = e.target as HTMLElement;
    if (!target.closest('.title-wrapper')) {
      showDropdown.value = false;
    }
  });
});

onUnmounted(() => {
  if (unsubscribe) {
    unsubscribe();
  }
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler);
  }
  if (fullscreenTimer) {
    window.clearTimeout(fullscreenTimer);
  }
  window.removeEventListener('keydown', escListener);
  disposeChart();
});
</script>

<style scoped>
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background: rgba(13, 27, 44, 0.95);
  border: 1px solid rgba(48, 65, 86, 0.6);
  border-radius: 4px;
  margin-top: 5px;
  z-index: 1000;
  min-width: 150px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.dropdown-item {
  padding: 8px 16px;
  color: #b0c4de;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 12px;
  white-space: nowrap;
}

.dropdown-item:hover {
  background: rgba(0, 150, 255, 0.2);
  color: #ffffff;
}

.dropdown-item.active {
  background: rgba(0, 150, 255, 0.3);
  color: #0096ff;
}

.dropdown-icon {
  cursor: pointer;
  transition: transform 0.2s;
}

.dropdown-icon:hover {
  transform: scale(1.1);
}
</style>
